<?php 

die();

/*
*	@auhor Robert Vasquez & Jason Kell
*	This program loads changes and new input
*	to the database for staff members
*	
*	Last Updated: November 2nd, 2009
*	@version 1.0
*/

// functions.php contains necessary data for this
// program to run such as info to connect to the db

require_once('../../includes/functions.php');

	//Get faculty information from
	$directoryRequest = new DirectoryRequest;
	$directoryRequest->connectDB();

require_once('../../settings.php');

// get the ID from the URL if it is present
// otherwise just send the user to the directory
if(isset($_GET['id']))
	$usId = $_GET['id'];
elseif(isset($_POST['new']))
{
	$add_new = 1;
	echo $add_new;
	die();
}
else
	header("Location:../");

//-----------------------------------------------

//An array to hold any errors that may be caused

$errors = array();

//-------------------------------------------------
	
// user info array from the form
$user_array = array(
	'usLname' => trim($_POST['last_name']),
	'usFname' => trim($_POST['first_name']),
	'usTitle' => trim($_POST['title']),
	'usJob' => trim($_POST['job']),
	'usEmail' => trim($_POST['email']),
	'usUser' => trim($_POST['user']),
	'usPerm' => trim($_POST['admin']),
	'usRoom' => trim($_POST['office']),
	'usPhone' => trim($_POST['phone']),
	'usSPhone' => trim($_POST['other_phone']),
	'usFax' => trim($_POST['fax']),
	'usWebsite' => trim($_POST['homepage']),
	'usLdesc' => trim($_POST['long_description']),
	'usEducation' => trim($_POST['education']),
	'usCourses' => trim($_POST['courses']),
	'usResearch' => trim($_POST['research']),
	'usSResearch' => trim($_POST['sresearch']),
	'usService' => trim($_POST['service']),
	'usSService' => trim($_POST['sservice']),
	'usSPublications' => trim($_POST['usSPublications']),
	'usPublications' => trim($_POST['publications']),
	'usAwards' => trim($_POST['sawards']),
	'usSAwards' => trim($_POST['sawards'])
);

//-------------------------------------------

//Array for job that are already set
$job_array = array();

//If job1 is full
if(isset($_POST['job1']))
{
	//Clean input and store in $job_array
	$job1 = trim($_POST['job1']);
	$job_array[1] = $job1;
}

//If job2 is full
if(isset($_POST['job2']))
{
	//Clean input and store in $job_array
	$job2 = trim($_POST['job2']);
	$job_array[2] = $job2;
}

//If job3 is full
if(isset($_POST['job3']))
{
	//Clean input and store in $job_array
	$job3 = trim($_POST['job3']);
	$job_array[3] = $job3;
}

//----------------

//Array for new jobs

$job_new_array = array();
//Checks for newly inputed job
if(isset($_POST['job1_new']) && $_POST['job1_new'] != 0)
{
	//Clean input and store in $job_array_new
	$job1_new = trim($_POST['job1_new']);
	$job_new_array[1] = $job1_new;
}
if(isset($_POST['job2_new']) && $_POST['job2_new'] != 0)
{
	//Clean input and store in $job_array_new
	$job2_new = trim($_POST['job2_new']);
	$job_new_array[2] = $job2_new;
}
if(isset($_POST['job3_new']) && $_POST['job3_new'] != 0)
{
	//Clean input and store in $job_array_new
	$job3_new = trim($_POST['job3_new']);
	$job_new_array[3] = $job3_new;
}

//---------------------------------------------------------

//Array for schools that are already set
$school_array = array();

//if school1 is full
if(isset($_POST['school1']))
{
	//Cleans blank space out of input from form and stores in school_array
	$school1 = trim($_POST['school1']);
	$school_array[1] = $school1;
}

//If school2 is full
if(isset($_POST['school2']))
{
	//Cleans blank space out of input from form and stores in school_array
	$school2 = trim($_POST['school2']);
	$school_array[2] = $school2;
}

//If school3 is full
if(isset($_POST['school3']))
{
	//Cleans blank space out of input from form and stores in school_array
	$school3 = trim($_POST['school3']);
	$school_array[3] = $school3;
}

//-------------------------------------

//Array for new schools

$school_new_array = array();
//If the user inputs a new school
if(isset($_POST['school1_new']) && $_POST['school1_new'] != 0)
{
	//Cleans blank space out of input from form and stores in school_array_new
	$school1_new = trim($_POST['school1_new']);
	$school_new_array[1] = $school1_new;
}
if(isset($_POST['school2_new']) && $_POST['school2_new'] != 0)
{
	//Cleans blank space out of input from form and stores in school_array_new
	$school2_new = trim($_POST['school2_new']);
	$school_new_array[2] = $school2_new;
}
if(isset($_POST['school3_new']) && $_POST['school3_new'] != 0)
{
	//Cleans blank space out of input from form and stores in school_array_new
	$school3_new = trim($_POST['school3_new']);
	$school_new_array[3] = $school3_new;
}

//-------------------------------------------------

//Array for the data from the connecting table
$connect_array = array();

//If connect1 exists
if(isset($_POST['connect_id_1']))
{
	//Cleans blank space out of input from form and stores in connect_array
	$connect_id_1 = trim($_POST['connect_id_1']);
	$connect_array[1] = $connect_id_1;
}
		
//If connect2 exists
if(isset($_POST['connect_id_2']))
{
	//Cleans blank space out of input from form and stores in connect_array
	$connect_id_2 = trim($_POST['connect_id_2']);
	$connect_array[2] = $connect_id_2;
}
		
//If connect3 exists
if(isset($_POST['connect_id_3']))
{
	//Cleans blank space out of input from form and stores in connect_array
	$connect_id_3 = trim($_POST['connect_id_3']);
	$connect_array[3] = $connect_id_3;
}

//-----------------------------------------

//Array for the data from the remove checkboxes
$remove_array = array();

if(isset($_POST['remove1']))
{
	//if a check box was set then remove data from DB
	$connect_id_1 = trim($_POST['connect_id_1']);
	
	if($connect_id_1 != "")
		$remove_array[1] = $_POST['remove1'];
		
}
	
if(isset($_POST['remove2']))
{
	//if a check box was set then remove data from DB
	$connect_id_2 = trim($_POST['connect_id_2']);
	
	if($connect_id_2 != "")
		$remove_array[2] = $_POST['remove2'];
}
if(isset($_POST['remove3']))
{
	//if a check box was set then remove data from DB
	$connect_id_3 = trim($_POST['connect_id_3']);
	
	if($connect_id_3 != "")
		$remove_array[3] = $_POST['remove3'];
}

//--------------------------------------------

if(!isset($add_new) && isset($usId))
{

	if($user_array['usFname'] != '' && $user_array['usLname'] != '' && $user_array['usUser'] != '' && $user_array['usEmail'] != '')
	{
		// Query for updating the user table in only sections that they DID edit
		
		// Pull the data from the table
		$sql = "SELECT * FROM Users WHERE usId='$usId'";
		$result = mssql_query($sql);
		//Convert Data pulled into an array
		$profile = mssql_fetch_assoc($result);
		
		// Each key that does not match will be updated
		// in this case individually
		foreach($user_array as $key => $vars)
		{
			//if anything has changed by comparing the input data to the current DB data
			if($vars != $profile[$key])
			{
				// If the user inputs an apostrophe(') it breaks the operation
				// To comment out an apostrophe(') in mssql input a second '
				$vars = str_replace("'", "''", $vars);
				
				//Store $vars in the newly constructed query.
				$sql = "UPDATE Users SET $key='" . $vars . "' WHERE usId='$usId'";
				//Run the query
				$result = mssql_query($sql);
			}
		}
	}
	
	if($job_array[1] != 8)
	{
		if ($user_array['usFname'] == '')
			$errors[] = 'You must include your first name.';
			
		if ($user_array['usLname'] == '')
			$errors[] = 'You must include your last name.';
			
		if ($user_array['usUser'] == '') 
			$errors[] = 'You must include your username.';
			
		if ($user_array['usEmail'] == '')
			$errors[] = 'You must include your email.';
	}
		
	//---------------------------------------------------------------
	
	//--------- Start job and school check and update system
	
	
	// The person may not have all 3 positions filled in
	// so we need to figure out how many rows to check
	
	// Count the number of occurrences in which both a new job
	// and a new school are selected
	
	//$c_total will be used to repeat the process of updating or adding
	// new jobs and schools based on the existing number of rows
	// and the number of rows being added
	if(count($job_new_array) !== 0 && count($school_new_array) !== 0)
	{
		// If the division of the new jobs by the new schools does not match
		// the user selected an improper group
		// so the operation will be ignored
		$divide = count($job_new_array) / count($school_new_array);
	
		// We need to add the connect_array to the job_new_array
		// to see how many new rows will be developed
		if($divide == 1)
			$c_total = count($connect_array) + count($job_new_array);
	}
	
	// If no rows in people_connect_tables exist for the user
	// and the user has not selected any new options for job and school
	// $c_total must equal one to operate properly in the for below
	elseif(count($connect_array) === 0)
		$c_total = 1;
	
	// if no new jobs have been selected, but there are rows for the user
	// the user may have edited but not added positions
	else
		$c_total = count($connect_array);
	
	// $c_total  is the total number of potential changes
	// Potential job and school changes
	// Potential job and school additions
	// Potential job and school removals
	
	// $c will increment until it matches the total number
	// of possible changes
	
	for($c = 1; $c <= $c_total; $c++)
	{
		// As long as there is more than 0 rows present for the user
		// in the people_connect table, it will check and see if any of the
		// existing rows are being updated
		if(count($connect_array) !== 0)
		{
			// if $c is less than but not equal to the total number of potential
			// changes, pull an array from the table that has a Connec_table_ID
			// matching the value from the $connect_array number for this instance
			// of the for operation
			if($c < count($c_total) + 1)
			{
				$sql = "SELECT * FROM people_connect_tables WHERE Connect_table_ID='" . $connect_array[$c] . "'";
				$result = mssql_query($sql);
				$pull = mssql_fetch_assoc($result);
	
	//-------- Start People_Type_ID check and update
	
				// if the pulled data of the People_Type_ID is different
				// from the data in the $job_array element for this instace
				// of the for operation, run an update
				if($pull['People_Type_ID'] != $job_array[$c])
				{
					$job_update = "UPDATE people_connect_tables SET People_Type_ID='" . $job_array[$c] . "' WHERE Connect_table_ID='" . $connect_array[$c] . "'";
					$result = mssql_query($job_update);	
				//break;
				}
	
	//-------- Start School_ID check and update
			
				// if the pulled data of the School_ID is different
				// from the data in the $school_array for this instance
				// of the for operation, run an update
				if($pull['School_ID'] != $school_array[$c])
				{
					$school_update = "UPDATE people_connect_tables SET School_ID='" . $school_array[$c] . "' WHERE Connect_table_ID='" . $connect_array[$c] . "'";
					$result = mssql_query($school_update);
					//break;	
				}
			}
		}
		
	//--------- Start remove position operation
	
		// If a remove box is checked prepare to remove a row
		if(isset($remove_array[$c]) == "on")
		{
			// Remove the rows with a Connect_table_ID that matches the
			// $connect_array value for this instance of the for operation
			$delete = "DELETE FROM people_connect_tables WHERE Connect_table_ID='" . $connect_array[$c] . "'";
			$result = mssql_query($delete);
			
		}
		
		// If a $job_new_array AND a $school_new_array element exist for
		// this instance of the for operation, insert a row
		if(isset($job_new_array[$c]) && isset($school_new_array[$c]))
		{
	
			$sql = "INSERT INTO people_connect_tables VALUES('$usId', '" . $job_new_array[$c] . "', '" . $school_new_array[$c] . "')";
			
			$result = mssql_query($sql) or die("SQL Error: " . mssql_get_last_message());
			
		}
		
		
	}
	// Ends for loop
	
	// If the user has registered a picture file to be uploaded
	// begin this operation to see if they already have a directory
	// and whether or not to upload the image
	if(isset($_FILES["image"]) && $_FILES["image"]["name"]!='')
	{
	
		/*	This piece would add a new directory for the staff member
		*	if they have not yet uploaded a file or photo
		*	Problem right now:
		*	the folder names are not uniform
		*	This would make all the folder names
		*	match there usUser
		*/
		
			//Check for a folder with a name that matches the username
			//If it does not exist, create one
			if(!is_dir("../../files/" . $user_array['usUser']))
				mkdir("../../files/" . $user_array['usUser']);
	
		/*	This piece will upload an image
		*	if the staff member has a folder
		*	with a name that matche their usUser
		*/
		
		
		// As long as the loaded image meets these requirements
		// the operation can continue
		if ($_FILES["image"]["size"] < 100000)
		{
		  move_uploaded_file($_FILES["image"]["tmp_name"],
		  "../../files/" . $user_array['usUser'] . "/" . $_FILES["image"]["name"]);
		  
			// Since a new image is being loaded, update the location
			// in the usImage column of the table
			if($_FILES["image"]["name"] == '')
			{
				$sql = "UPDATE users SET usImage='files/" . $user_array['usUser'] . "/" . $_FILES["image"]["name"] . "' WHERE usId='$usId'";
				$result = mssql_query($sql) or die(mssql_get_last_message());
			}
			$sql = "UPDATE users SET usImage='files/" . $user_array['usUser'] . "/" . $_FILES["image"]["name"] . "' WHERE usId='$usId'";
			$result = mssql_query($sql) or die(mssql_get_last_message());
		 }
		 else
			$errors[] = 'Your image may only be a .gif or .jpg and less than 100kb';
	}
	
	// If the user has registered a doc file to be uploaded
	// begin this operation to see if they already have a directory
	// and whether or not to upload the image
	if(isset($_FILES["cv"]) && $_FILES["cv"]["name"] != '')
	{
	
		/*	This piece would add a new directory for the staff member
		*	if they have not yet uploaded a file or photo
		*	Problem right now:
		*	the folder names are not uniform
		*	This would make all the folder names
		*	match there usUser
		*/
		
			//Check for a folder with a name that matches the username
			//If it does not exist, create one
			if(!is_dir("../../files/" . $user_array['usUser']))
				mkdir("../../files/" . $user_array['usUser']);
	
		/*	This piece will upload a file
		*	if the staff member has a folder
		*	with a name that matche their usUser
		*/
		
		
		// As long as the loaded file meets these requirements
		// the operation can continue
		if (($_FILES["cv"]["size"] < 200000))
		{
		  move_uploaded_file($_FILES["cv"]["tmp_name"],
		  "../../files/" . $user_array['usUser'] . "/" . $_FILES["cv"]["name"]);
		  
			// Since a new file is being loaded, update the location
			// in the usImage column of the table
			$sql = "UPDATE users SET usCV='files/" . $user_array['usUser'] . "/" . $_FILES["cv"]["name"] . "' WHERE usId='$usId'";
			$result = mssql_query($sql) or die(mssql_get_last_message());
		 }
		 else
			$errors[] = 'Your file may only be a .doc, .docx, .txt, .pdf, .rtf, or .tiff and less than 200kb.';
	}
	
	if(count($errors) > 0)
	{
		$count = count($errors);
			
		header("Location:../edit.php?id=$usId&errors=$count");
		die();
	}
	
	// If the entire operation has completed successfully
	// return to their editing page
	
	header("Location:".$_SERVER['HTTP_HOST'] ."/faculty_staff/mgr/profile.php?id=$usId");

}

elseif(isset($add_new) && $add_new == 1)
{

}
